'use strict';

// 云对象名：exam-service
module.exports = {
  getVersion() {
    return '2.0.0'
  },

  /**
   * 获取考试列表
   * @param {object} params - 参数对象
   * @param {string} params.type - 考试类型
   * @param {boolean} params.onlyNames - 是否只获取名称信息
   * @param {string} params.creatorId - 创建者ID
   * @returns {object} 考试列表
   */
  async getExamList(params) {
    try {
      // 获取数据库引用
      const db = uniCloud.database();
      
      const { type, onlyNames, creatorId } = params;
      console.log('查询条件:', { type, onlyNames, creatorId });
      
      // 构建查询条件
      const where = {};
      if (type) {
        where.exam_type = type;
      }
      if (creatorId) {
        where.creator_id = creatorId;
      }
      
      console.log('最终查询条件:', where);
      
      // 查询考试列表
      const examList = await db.collection('exam_papers')
        .where(where)
        .orderBy('create_date', 'desc')
        .get()
        .then(res => {
          console.log('数据库查询结果:', res);
          return res.data || [];
        });
      
      console.log('查询到的考试数量:', examList.length);
      
      // 处理返回数据 - 这里只返回考试基本信息，不包含状态
      const result = examList.map(item => {
        // 如果只需要名称信息，返回精简数据
        if (onlyNames) {
          return {
            _id: item._id,
            title: item.title || '未命名考试',
            creator_id: item.creator_id || '',
            create_time: item.create_date ? item.create_date.getTime() : Date.now()
          };
        }
        
        // 构建返回数据
        return {
          _id: item._id,
          title: item.title || '未命名考试',
          description: item.description || '',
          duration: item.time_limit || 60,
          question_count: (item.questions && Array.isArray(item.questions)) ? item.questions.length : 0,
          pass_score: item.pass_score || 60,
          type: item.exam_type || '',
          status: 'available', // 默认状态为可参加
          create_time: item.create_date ? item.create_date.getTime() : Date.now()
        };
      });
      
      return {
        code: 0,
        message: '查询成功',
        data: result
      };
    } catch (error) {
      console.error('获取考试列表失败:', error);
      return {
        code: -1,
        message: '获取考试列表失败: ' + error.message,
        error: error
      };
    }
  },

  /**
   * 获取考试详情
   * @param {string|object} params - 考试ID或参数对象
   * @param {string} params.examId - 考试ID（当传入对象时）
   * @returns {object} 考试详情
   */
  async getExamDetail(params) {
    // 兼容处理：支持直接传入examId字符串或对象参数
    let examId;
    
    if (typeof params === 'string') {
      examId = params;
    } else if (typeof params === 'object' && params) {
      examId = params.examId || params.id;
    }
    
    if (!examId) {
      return {
        code: -1,
        message: '考试ID不能为空'
      };
    }

    try {
      const db = uniCloud.database();
      
      // 查询考试详情
      const examResult = await db.collection('exam_papers')
        .doc(examId)
        .get();
      
      if (!examResult.data || examResult.data.length === 0) {
        return {
          code: -1,
          message: '考试不存在'
        };
      }
      
      const examData = Array.isArray(examResult.data) ? examResult.data[0] : examResult.data;
      
      // 获取题目详情
      if (examData.questions && Array.isArray(examData.questions) && examData.questions.length > 0) {
        try {
          const questionsResult = await db.collection('exam_questions')
            .where({
              _id: db.command.in(examData.questions)
            })
            .get();
            
          if (questionsResult.data) {
            // 按照试卷中的题目顺序排序
            const questionsMap = {};
            questionsResult.data.forEach(q => {
              questionsMap[q._id] = q;
            });
            
            examData.questions = examData.questions.map(qId => {
              const question = questionsMap[qId];
              if (!question) {
                console.warn('题目不存在:', qId);
                return null;
              }
              return question;
            }).filter(q => q !== null);
            
            console.log('获取到题目数量:', examData.questions.length);
          }
        } catch (error) {
          console.error('获取题目详情失败:', error);
        }
      }
      
      return {
        code: 0,
        message: '获取成功',
        data: examData
      };
    } catch (error) {
      console.error('获取考试详情失败:', error);
      return {
        code: -1,
        message: '获取考试详情失败: ' + error.message
      };
    }
  },

  /**
   * 提交考试
   * @param {object} params - 提交参数
   * @param {string} params.examId - 考试ID
   * @param {array} params.userAnswers - 用户答案
   * @param {number} params.usedTime - 用时
   * @param {object} params.userInfo - 用户信息
   * @param {string} params.token - 用户token
   * @returns {object} 提交结果
   */
  async submitExam(params) {
    try {
      // 获取数据库引用
      const db = uniCloud.database();
      
      const { examId, userAnswers, usedTime, userInfo, token } = params;
      
      // 验证参数
      if (!examId) {
        return {
          code: -1,
          message: '缺少考试ID'
        };
      }
      
      if (!Array.isArray(userAnswers) || userAnswers.length === 0) {
        return {
          code: -1,
          message: '答案数据格式错误'
        };
      }
      
      console.log('接收到的考试提交:', {
        examId,
        answersCount: userAnswers.length,
        usedTime
      });
      
      // 获取用户信息
      let currentUserId = 'anonymous';
      
      // 1. 尝试从请求参数中获取用户信息
      if (userInfo && userInfo._id) {
        currentUserId = userInfo._id;
        console.log('从请求参数中获取用户ID:', currentUserId);
      }
      
      // 2. 尝试从token中获取用户信息
      if (currentUserId === 'anonymous' && token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
            console.log('从token成功获取用户ID:', currentUserId);
          }
        } catch (tokenError) {
          console.error('解析token失败:', tokenError);
        }
      }
      
      // 3. 如果仍然是匿名用户，拒绝提交
      if (currentUserId === 'anonymous') {
        console.error('用户未登录或身份验证失败');
        return {
          code: -2,
          message: '请先登录后再提交考试'
        };
      }
      
      // 获取考试信息
      let examInfo = {};
      let examTitle = '未命名考试';
      let questions = [];
      
      try {
        const examPaperResult = await db.collection('exam_papers')
          .doc(examId)
          .get();
        
        if (examPaperResult && examPaperResult.data) {
          examInfo = Array.isArray(examPaperResult.data) ? examPaperResult.data[0] : examPaperResult.data;
          examTitle = examInfo.title || examInfo.exam_title || examInfo.name || examTitle;
          
          // 获取题目详情
          if (examInfo.questions && Array.isArray(examInfo.questions)) {
            const questionIds = examInfo.questions.map(q => q._id || q);
            const questionsResult = await db.collection('exam_questions')
              .where({
                _id: db.command.in(questionIds)
              })
              .get();
            
            if (questionsResult && questionsResult.data) {
              questions = questionsResult.data;
              console.log('获取到题目数量:', questions.length);
            }
          }
        }
      } catch (error) {
        console.error('获取考试信息失败:', error);
        return {
          code: -1,
          message: '获取考试信息失败'
        };
      }
      
      // 如果没有获取到题目，返回错误
      if (!questions || questions.length === 0) {
        console.error('未找到考试题目');
        return {
          code: -1,
          message: '未找到考试题目'
        };
      }
      
      // 计算考试得分
      let totalScore = 0;
      let correctCount = 0;
      const totalQuestions = questions.length;
      
      // 创建题目ID到题目的映射，方便查找
      const questionMap = {};
      questions.forEach(q => {
        questionMap[q._id] = q;
      });
      
      // 遍历用户答案计算分数
      for (const answer of userAnswers) {
        const question = questionMap[answer.questionId];
        if (!question) continue;
        
        let isCorrect = false;
        
        // 根据题型判断答案是否正确
        if (question.type === 'judge' || question.type === 'judgment') {
          // 判断题
          isCorrect = answer.answer === question.correct_option;
        } else if (question.type === 'multiple') {
          // 多选题，需要数组完全匹配
          const userAnswerSet = new Set(answer.answer);
          const correctAnswerSet = new Set(question.correct_options);
          isCorrect = userAnswerSet.size === correctAnswerSet.size &&
            [...userAnswerSet].every(value => correctAnswerSet.has(value));
        } else {
          // 单选题
          isCorrect = answer.answer === question.correct_option;
        }
        
        if (isCorrect) {
          totalScore += (question.score || 5);
          correctCount++;
        }
      }

      // 判断是否及格
      const passScore = examInfo.pass_score || 60;
      const isPassed = totalScore >= passScore;

      // 准备考试记录
      const examRecord = {
        exam_id: examId,
        user_id: currentUserId,
        user_name: userInfo.nickname || userInfo.realname || '',
        exam_title: examTitle,
        total_score: totalScore,
        pass_score: passScore,
        is_passed: isPassed,
        used_time: usedTime,
        answers: userAnswers,
        correct_count: correctCount,
        total_questions: totalQuestions,
        submit_time: new Date(),
        status: 'completed'
      };
      
      // 保存考试记录
      const saveResult = await db.collection('exam_records').add(examRecord);
      
      if (saveResult.id) {
        console.log('考试记录保存成功，记录ID:', saveResult.id);
        
        return {
          code: 0,
          message: '考试提交成功',
          data: {
            recordId: saveResult.id,
            score: totalScore,
            correctCount: correctCount,
            totalQuestions: totalQuestions,
            isPassed: isPassed,
            passScore: passScore
          }
        };
      } else {
        console.error('考试记录保存失败');
        return {
          code: -1,
          message: '提交失败，请重试'
        };
      }
    } catch (error) {
      console.error('提交考试失败:', error);
      return {
        code: -1,
        message: '提交失败: ' + error.message,
        error: error
      };
    }
  },

  /**
   * 获取考试结果
   * @param {string} recordId - 记录ID
   * @returns {object} 考试结果
   */
  async getExamResult(recordId) {
    console.log('getExamResult 接收到请求参数:', recordId);
      
    // 检查recordId格式
    if (!recordId || typeof recordId !== 'string' || recordId.length !== 24) {
        console.error('考试记录ID格式不正确:', recordId);
        return {
          code: -1,
            message: '考试记录ID格式不正确'
        };
      }
      
      try {
        // 获取数据库引用
        const db = uniCloud.database();
        
        console.log('开始获取考试记录:', recordId);
          
        // 获取考试记录
        const recordResult = await db.collection('exam_records')
            .doc(recordId)
            .get();
          
        if (!recordResult.data || !recordResult.data.length) {
            console.error('考试记录不存在:', recordId);
            return {
              code: -1,
                message: '考试记录不存在'
            };
        }
        
        const examRecord = recordResult.data[0];
        console.log('获取到考试记录:', examRecord);
        
        // 获取试卷信息
        const examResult = await db.collection('exam_papers')
            .doc(examRecord.exam_id)
            .get();
          
        if (!examResult.data || !examResult.data.length) {
            console.error('试卷信息不存在:', examRecord.exam_id);
            return {
              code: -1,
                message: '试卷信息不存在'
            };
          }
        
        const examPaper = examResult.data[0];
        console.log('获取到试卷信息:', examPaper);
        
        // 获取题目详情
        const questionIds = examRecord.answers.map(a => a.question_id);
        console.log('题目ID列表:', questionIds);
        
          const questionsResult = await db.collection('exam_questions')
            .where({
              _id: db.command.in(questionIds)
            })
            .get();
            
        if (!questionsResult.data) {
            console.error('获取题目详情失败');
            return {
                code: -1,
                message: '获取题目详情失败'
            };
        }
        
        console.log('获取到题目数量:', questionsResult.data.length);
        
        // 构建题目映射
        const questionsMap = {};
        questionsResult.data.forEach(q => {
            questionsMap[q._id] = q;
        });
        
        // 合并答题记录和题目信息，并判断答案正确性
        const questions = examRecord.answers.map(answer => {
            const question = questionsMap[answer.question_id];
            if (!question) return null;
            
            // 判断答案正确性
            let isCorrect = false;
            if (question.type === 'single') {
                // 单选题 - 直接比较
                isCorrect = String(question.correct_answer) === String(answer.user_answer);
            } else if (question.type === 'multiple') {
                // 多选题 - 数组比较
                const correctAnswers = Array.isArray(question.correct_answer) ? 
                    question.correct_answer.map(String).sort() : 
                    [String(question.correct_answer)];
                    
                const userAnswers = Array.isArray(answer.user_answer) ? 
                    answer.user_answer.map(String).sort() : 
                    [String(answer.user_answer)];
                    
                isCorrect = correctAnswers.length === userAnswers.length &&
                    correctAnswers.every((val, idx) => val === userAnswers[idx]);
            } else if (question.type === 'judgment' || question.type === 'judge') {
                // 判断题 - 转换为布尔值比较
                const correctAnswer = ['true', '1', 'yes'].includes(String(question.correct_answer).toLowerCase());
                const userAnswer = ['true', '1', 'yes'].includes(String(answer.user_answer).toLowerCase());
                isCorrect = correctAnswer === userAnswer;
            }
            
            return {
            ...question,
                user_answer: answer.user_answer,
                is_correct: isCorrect,
                time_spent: answer.time_spent || 0
            };
        }).filter(q => q !== null);
        
        // 计算总分和正确题数
        let totalScore = 0;
        let correctCount = 0;
        questions.forEach(q => {
            if (q.is_correct) {
                correctCount++;
                totalScore += (q.score || 0);
            }
        });
        
        // 构建返回数据
        const result = {
            score: totalScore, // 直接使用计算得到的分数
            pass_score: examPaper.pass_score || 60,
            total_questions: questions.length,
            correct_count: correctCount,
            used_time: examRecord.duration || 0, // 确保有默认值
            avg_time_per_question: questions.length > 0 ? Math.round((examRecord.duration || 0) / questions.length) : 0,
            questions: questions,
            exam_id: examRecord.exam_id,
            title: examPaper.title
        };
        
        console.log('返回结果:', result);
        
        return {
          code: 0,
          message: '获取成功',
            data: result
        };
    } catch (err) {
        console.error('获取考试结果失败:', err);
        return {
          code: -1,
            message: '获取考试结果失败: ' + err.message
      };
    }
  },
  
  // 获取正确答案
  getCorrectAnswer(question) {
    if (!question) return null;
    
    if (question.type === 'single') {
      // 单选题 - 确保返回字符串
      const answer = question.correct_option !== undefined ? question.correct_option : 
        (question.correct_answer !== undefined ? question.correct_answer : '0');
      return String(answer);
    } else if (question.type === 'multiple') {
      // 多选题 - 确保返回字符串数组
      const answers = question.correct_options || question.correct_answer || [];
      return Array.isArray(answers) ? answers.map(String) : [String(answers)];
    } else if (question.type === 'judge' || question.type === 'judgment') {
      // 判断题 - 确保返回字符串
      const answer = question.correct_option !== undefined ? question.correct_option : 
        (question.correct_answer !== undefined ? question.correct_answer : 'true');
      return String(answer);
    }
    
    return null;
  },
  
  // 计算正确答案与用户答案的比较结果
  determineIfCorrect(type, correct, user) {
    console.log(`判断正确性 - 类型:${type}, 正确答案:${JSON.stringify(correct)}, 用户答案:${JSON.stringify(user)}`);
    
    try {
      if (type === 'single') {
        // 单选题 - 使用0-based索引
        return Number(correct) === Number(user);
      } else if (type === 'multiple') {
        // 多选题 - 使用0-based索引数组
        if (!Array.isArray(correct) || !Array.isArray(user)) {
          // 如果用户答案是字符串，尝试解析为数组
          let userArray = user;
          if (typeof user === 'string') {
            try {
              userArray = JSON.parse(user);
            } catch (e) {
              userArray = user.split(',');
            }
          }
          
          if (!Array.isArray(userArray)) {
            return false;
          }
          
          // 确保correct也是数组
          const correctArray = Array.isArray(correct) ? correct : [correct];
          
          // 转换为数字后比较
          const sortedCorrect = correctArray.map(Number).sort((a, b) => a - b);
          const sortedUser = userArray.map(Number).sort((a, b) => a - b);
          
          return sortedCorrect.length === sortedUser.length && 
            sortedCorrect.every((val, idx) => val === sortedUser[idx]);
        }
        
        // 转换为数字后比较
        const sortedCorrect = correct.map(Number).sort((a, b) => a - b);
        const sortedUser = user.map(Number).sort((a, b) => a - b);
        
        return sortedCorrect.length === sortedUser.length && 
          sortedCorrect.every((val, idx) => val === sortedUser[idx]);
      } else if (type === 'judgment' || type === 'judge') {
        // 判断题 - 统一使用布尔值
        const correctBool = typeof correct === 'boolean' ? correct :
          (correct === 'true' || correct === '1' || correct === 1);
        const userBool = typeof user === 'boolean' ? user :
          (user === 'true' || user === '1' || user === 1);
        return correctBool === userBool;
      }
    } catch (error) {
      console.error('比较答案时出错:', error);
      return false;
    }
    
    return false;
  },
  
  // 处理选项
  processOptions(options) {
    if (!options) return [];
    
    // 如果是对象数组，提取内容
    if (Array.isArray(options) && options.length > 0 && typeof options[0] === 'object') {
      return options.map(opt => {
        if (opt && opt.content !== undefined) {
          return opt.content;
        }
        return JSON.stringify(opt);
      });
    }
    
    // 确保返回数组
    return Array.isArray(options) ? options : [];
  },

  /**
   * 获取考试记录
   * @param {object} params - 参数对象
   * @param {number} params.page - 页码
   * @param {number} params.pageSize - 每页数量
   * @param {string} params.token - 用户token
   * @param {object} params.userInfo - 用户信息对象
   * @returns {object} 考试记录列表
   */
  async getExamRecords(params) {
    try {
      const db = uniCloud.database();
      
      // 参数处理
      const page = params.page || 1;
      const limit = params.pageSize || 10;
      const userInfo = params.userInfo || {};
      
      // 验证用户信息
      if (!userInfo._id) {
        console.error('缺少用户ID');
        return {
          code: -1,
          message: '未获取到用户信息'
        };
      }
      
      console.log('获取考试记录，用户ID:', userInfo._id);
      
      // 构建查询条件
      const where = {
        user_id: userInfo._id,
        status: 'completed' // 只获取已完成的考试记录
      };
      
      // 计算跳过的记录数
      const skip = (page - 1) * limit;
      
      console.log('查询条件:', where);
      console.log('分页参数:', { page, limit, skip });
      
      // 查询考试记录
      const recordsResult = await db.collection('exam_records')
        .where(where)
        .orderBy('submit_time', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      console.log('查询结果:', recordsResult);
      
      // 查询总数
      const countResult = await db.collection('exam_records')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: recordsResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
        }
      };
    } catch (error) {
      console.error('获取考试记录失败:', error);
      return {
        code: -1,
        message: '获取考试记录失败: ' + error.message
      };
    }
  },

  /**
   * 上传试卷
   * @param {object} params - 参数对象
   * @param {string} params.title - 试卷标题
   * @param {string} params.description - 试卷描述
   * @param {string} params.exam_type - 考试类型
   * @param {number} params.time_limit - 时间限制
   * @param {number} params.pass_score - 及格分
   * @param {number} params.total_score - 总分
   * @param {array} params.questions - 题目数组
   * @param {string} params.cover_image - 封面图片
   * @param {boolean} params.is_published - 是否发布
   * @param {string} params.status - 状态
   * @param {array} params.media_files - 媒体文件
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @returns {object} 上传结果
   */
  async uploadExamPaper(params) {
    try {
      // 获取数据库引用
      const db = uniCloud.database();
      
      // 参数解构
      const {
        title,
        description,
        exam_type,
        time_limit,
        pass_score,
        total_score,
        questions,
        cover_image,
        is_published,
        status,
        media_files,
        userId,
        token
      } = params;
      
      console.log('上传试卷开始，参数:', {
        title, description, exam_type, time_limit, pass_score, total_score,
        questionCount: questions ? questions.length : 0,
        cover_image, is_published, status,
        mediaFilesCount: media_files ? media_files.length : 0,
        userId: userId,
        hasToken: !!token
      });
      
      // 验证用户身份和token
      let currentUserId = '';
      let currentUserInfo = null;
      
      if (userId) {
        currentUserId = userId;
        console.log('从参数获取用户ID:', currentUserId);
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
            token: token
          });
          
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
            currentUserInfo = tokenRes.userInfo;
            console.log('从token获取到用户ID:', currentUserId);
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }
      
      // 验证用户ID
      if (!currentUserId) {
        console.error('未能获取有效的用户ID');
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }
      
      // 验证用户权限 - 检查是否为管理员
      if (currentUserInfo && currentUserInfo.role !== 4 && currentUserInfo.role !== '4') {
        return {
          code: 403,
          message: '权限不足，仅管理员可以发布试卷'
        };
      }
      
      // 验证必填参数
      if (!title || !description || !exam_type || !questions || questions.length === 0) {
        return {
          code: -1,
          message: '请填写完整信息'
        };
      }

      // 先保存所有题目到exam_questions集合
      const questionIds = [];
      for (const question of questions) {
        try {
          // 构建题目数据
          const questionData = {
            title: question.title,
            type: question.type,
            options: question.options || [],
            correct_answer: question.correct_answer,
            correct_option: question.correct_option,
            correct_options: question.correct_options,
            score: question.score || 0,
            analysis: question.analysis || '',
            explanation: question.explanation || '',
            media_files: question.media_files || [],
            create_date: new Date(),
            update_date: new Date(),
            creator_id: currentUserId
          };

          // 保存题目
          const result = await db.collection('exam_questions').add(questionData);
          if (result.id) {
            questionIds.push(result.id);
          }
        } catch (error) {
          console.error('保存题目失败:', error);
        }
      }

      // 如果没有成功保存任何题目，返回错误
      if (questionIds.length === 0) {
        return {
          code: -1,
          message: '题目保存失败'
        };
      }
      
      // 创建试卷记录，使用一致的命名风格（下划线）
      const examData = {
        title,
        description,
        exam_type: exam_type,
        time_limit: parseInt(time_limit) || 60,
        pass_score: parseInt(pass_score) || 60,
        total_score: parseInt(total_score) || 100,
        questions: questionIds, // 只保存题目ID列表
        cover_image: cover_image || '',
        is_published: !!is_published,
        status: status || 'active',
        create_date: new Date(),
        update_date: new Date(),
        creator_id: currentUserId,
        creatorId: currentUserId,
        author_id: currentUserId,
        user_id: currentUserId,
        view_count: 0,
        attempt_count: 0,
        pass_count: 0
      };
      
      // 如果有媒体文件，添加到试卷数据中
      if (media_files && Array.isArray(media_files) && media_files.length > 0) {
        examData.media_files = media_files;
        console.log('添加媒体文件到试卷:', media_files.length, '个文件');
      }
      
      console.log('准备保存的试卷数据:', {
        title: examData.title,
        creator_id: examData.creator_id,
        questionCount: questionIds.length
      });
      
      const result = await db.collection('exam_papers').add(examData);
      
      console.log('试卷保存结果:', result);
      
      return {
        code: 0,
        message: '试卷上传成功',
        data: {
          id: result.id,
          examId: result.id,
          questionIds: questionIds
        }
      };
    } catch (error) {
      console.error('试卷上传错误：', error);
      return {
        code: -1,
        message: '上传失败：' + error.message
      };
    }
  },

  /**
   * 更新考试
   * @param {object} params - 参数对象
   * @param {string} params.examId - 考试ID
   * @param {string} params.title - 标题
   * @param {string} params.description - 描述
   * @param {string} params.exam_type - 考试类型
   * @param {number} params.time_limit - 时间限制
   * @param {number} params.pass_score - 及格分
   * @param {number} params.total_score - 总分
   * @param {array} params.questions - 题目
   * @param {string} params.cover_image - 封面图片
   * @param {boolean} params.is_published - 是否发布
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {array} params.media_files - 媒体文件
   * @returns {object} 更新结果
   */
  async updateExam(params) {
    const db = uniCloud.database();
    const examsCollection = db.collection('exam_papers');
    
    try {
      // 参数解构
      const {
        examId,
        title,
        description,
        exam_type,
        time_limit,
        pass_score,
        total_score,
        questions,
        cover_image,
        is_published,
        userId,
        token,
        media_files
      } = params;
      
      // 验证考试ID
      if (!examId) {
        return {
          code: -1,
          message: '考试ID不能为空'
        };
      }

      // 验证用户身份和token
      let currentUserId = '';
      let currentUserInfo = null;
      
      if (userId) {
        currentUserId = userId;
        console.log('从参数获取用户ID:', currentUserId);
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
            token: token
          });
          
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
            currentUserInfo = tokenRes.userInfo;
            console.log('从token获取到用户ID:', currentUserId);
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }

      if (!currentUserId) {
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }

      // 获取原有试卷信息
      const examResult = await examsCollection.doc(examId).get();
      if (!examResult.data || examResult.data.length === 0) {
        return {
          code: -1,
          message: '考试不存在'
        };
      }

      const oldExam = Array.isArray(examResult.data) ? examResult.data[0] : examResult.data;
      
      // 检查权限
      if (oldExam.creator_id !== currentUserId && oldExam.author_id !== currentUserId && oldExam.user_id !== currentUserId) {
        return {
          code: 403,
          message: '无权限修改此考试'
        };
      }
      
      const oldQuestionIds = oldExam.questions || [];

      // 处理新的题目列表
      const questionIds = [];
      if (questions && Array.isArray(questions)) {
        for (const question of questions) {
          try {
            let questionId = question._id; // 如果是已有题目

            if (!questionId) {
              // 新题目，保存到exam_questions
              const questionData = {
                title: question.title,
                type: question.type,
                options: question.options || [],
                correct_answer: question.correct_answer,
                correct_option: question.correct_option,
                correct_options: question.correct_options,
                score: question.score || 0,
                analysis: question.analysis || '',
                explanation: question.explanation || '',
                media_files: question.media_files || [],
                create_date: new Date(),
                update_date: new Date(),
                creator_id: currentUserId
              };

              const result = await db.collection('exam_questions').add(questionData);
              questionId = result.id;
            } else {
              // 更新已有题目
              const questionData = {
                title: question.title,
                type: question.type,
                options: question.options || [],
                correct_answer: question.correct_answer,
                correct_option: question.correct_option,
                correct_options: question.correct_options,
                score: question.score || 0,
                analysis: question.analysis || '',
                explanation: question.explanation || '',
                media_files: question.media_files || [],
                update_date: new Date()
              };

              await db.collection('exam_questions').doc(questionId).update(questionData);
            }

            questionIds.push(questionId);
          } catch (error) {
            console.error('处理题目失败:', error);
          }
        }
      }

      // 删除不再使用的题目
      const removedQuestionIds = oldQuestionIds.filter(id => !questionIds.includes(id));
      if (removedQuestionIds.length > 0) {
        try {
          await db.collection('exam_questions')
            .where({
              _id: db.command.in(removedQuestionIds),
              creator_id: currentUserId // 只删除当前用户创建的题目
            })
            .remove();
        } catch (error) {
          console.error('删除旧题目失败:', error);
        }
      }

      // 更新试卷信息
      const updateData = {
        title,
        description,
        exam_type,
        time_limit: parseInt(time_limit) || 60,
        pass_score: parseInt(pass_score) || 60,
        total_score: parseInt(total_score) || 100,
        questions: questionIds,
        cover_image: cover_image || '',
        is_published: !!is_published,
        update_date: new Date()
      };

      if (media_files && Array.isArray(media_files)) {
        updateData.media_files = media_files;
      }

      // 更新试卷
      await examsCollection.doc(examId).update(updateData);

      return {
        code: 0,
        message: '更新成功',
        data: {
          id: examId,
          examId: examId,
          questionIds: questionIds
        }
      };
    } catch (error) {
      console.error('更新考试失败:', error);
      return {
        code: -1,
        message: '更新失败: ' + error.message
      };
    }
  },

  /**
   * 删除考试
   * @param {object} params - 参数对象
   * @param {string} params.examId - 考试ID
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @returns {object} 删除结果
   */
  async deleteExam(params) {
    try {
      const db = uniCloud.database();
      
      // 参数解构
      const { examId, userId, token } = params;
      
      if (!examId) {
        return {
          code: -1,
          message: '考试ID不能为空'
        };
      }
      
      // 验证用户身份和token
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
        console.log('从参数获取用户ID:', currentUserId);
      } else if (token) {
        // 使用uni-id-co验证token
        const uniIdCo = uniCloud.importObject('uni-id-co');
        try {
          const tokenRes = await uniIdCo.checkToken({
          token: token
          });
        
          if (tokenRes.code === 0 && tokenRes.uid) {
            currentUserId = tokenRes.uid;
            console.log('从token获取到用户ID:', currentUserId);
          } else {
            return {
              code: 401,
              message: '无效的token，请重新登录'
            };
          }
        } catch (error) {
          console.error('token验证失败:', error);
          return {
            code: 401,
            message: '身份验证失败，请重新登录'
          };
        }
      }
      
      if (!currentUserId) {
        return {
          code: 401,
          message: '未授权，无法获取用户信息'
        };
      }
      
      // 查询考试信息
      const examResult = await db.collection('exam_papers').doc(examId).get();
      if (!examResult.data || examResult.data.length === 0) {
        return {
          code: -1,
          message: '考试不存在'
        };
      }
      
      const exam = Array.isArray(examResult.data) ? examResult.data[0] : examResult.data;
      
      // 检查权限
      if (exam.creator_id !== currentUserId && exam.author_id !== currentUserId && exam.user_id !== currentUserId) {
        return {
          code: 403,
          message: '无权限删除此考试'
        };
      }
      
      // 删除考试相关的题目
      if (exam.questions && Array.isArray(exam.questions) && exam.questions.length > 0) {
        try {
          await db.collection('exam_questions')
            .where({
              _id: db.command.in(exam.questions),
              creator_id: currentUserId // 只删除当前用户创建的题目
            })
            .remove();
        } catch (error) {
          console.error('删除题目失败:', error);
        }
      }
      
      // 删除考试
      await db.collection('exam_papers').doc(examId).remove();
      
      return {
        code: 0,
        message: '删除成功'
      };
    } catch (error) {
      console.error('删除考试失败:', error);
      return {
        code: -1,
        message: '删除失败: ' + error.message
      };
    }
  },

  /**
   * 获取考试统计
   * @param {string} examId - 考试ID
   * @returns {object} 统计数据
   */
  async getExamStatistics(examId) {
    try {
      const db = uniCloud.database();
      
      if (!examId) {
        return {
          code: -1,
          message: '考试ID不能为空'
        };
      }
      
      // 获取考试记录统计
      const recordsResult = await db.collection('exam_records')
        .where({
          exam_id: examId
        })
        .get();
      
      const records = recordsResult.data || [];
      
      // 计算统计数据
      const totalAttempts = records.length;
      const passedCount = records.filter(record => record.is_passed).length;
      const averageScore = totalAttempts > 0 
        ? Math.round(records.reduce((sum, record) => sum + record.score, 0) / totalAttempts)
        : 0;
      
      // 分数分布
      const scoreDistribution = {
        '0-59': 0,
        '60-69': 0,
        '70-79': 0,
        '80-89': 0,
        '90-100': 0
      };
      
      records.forEach(record => {
        const score = record.score;
        if (score < 60) scoreDistribution['0-59']++;
        else if (score < 70) scoreDistribution['60-69']++;
        else if (score < 80) scoreDistribution['70-79']++;
        else if (score < 90) scoreDistribution['80-89']++;
        else scoreDistribution['90-100']++;
      });
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          totalAttempts,
          passedCount,
          passRate: totalAttempts > 0 ? Math.round((passedCount / totalAttempts) * 100) : 0,
          averageScore,
          scoreDistribution
        }
      };
    } catch (error) {
      console.error('获取考试统计失败:', error);
      return {
        code: -1,
        message: '获取统计失败: ' + error.message
      };
    }
  },

  /**
   * 分享考试
   * @param {string} examId - 考试ID
   * @param {string} userId - 用户ID
   * @returns {object} 分享结果
   */
  async shareExam(examId, userId) {
    try {
      const db = uniCloud.database();
      
      if (!examId || !userId) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 记录分享行为
      await db.collection('exam_shares').add({
        exam_id: examId,
        user_id: userId,
        share_time: new Date(),
        create_time: Date.now()
      });
      
      // 更新考试分享次数
      await db.collection('exam_papers').doc(examId).update({
        share_count: db.command.inc(1)
      });
      
      return {
        code: 0,
        message: '分享成功'
      };
    } catch (error) {
      console.error('分享考试失败:', error);
      return {
        code: -1,
        message: '分享失败: ' + error.message
      };
    }
  },

  /**
   * 更新考试状态
   * @param {string} examId - 考试ID
   * @param {string} status - 状态
   * @param {string} userId - 用户ID
   * @returns {object} 更新结果
   */
  async updateExamStatus(examId, status, userId) {
    try {
      const db = uniCloud.database();
      
      if (!examId || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 验证用户权限
      const examResult = await db.collection('exam_papers').doc(examId).get();
      if (!examResult.data || examResult.data.length === 0) {
        return {
          code: -1,
          message: '考试不存在'
        };
      }
      
      const exam = Array.isArray(examResult.data) ? examResult.data[0] : examResult.data;
      
      if (exam.creator_id !== userId && exam.author_id !== userId) {
        return {
          code: -1,
          message: '无权限修改此考试状态'
        };
      }
      
      // 更新状态
      await db.collection('exam_papers').doc(examId).update({
        status: status,
        update_date: new Date()
      });
      
      return {
        code: 0,
        message: '状态更新成功'
      };
    } catch (error) {
      console.error('更新考试状态失败:', error);
      return {
        code: -1,
        message: '更新状态失败: ' + error.message
      };
    }
  },

  /**
   * 保存题目
   * @param {object} params - 题目参数
   * @param {string} params.title - 题目标题
   * @param {string} params.type - 题目类型
   * @param {array} params.options - 选项列表
   * @param {string} params.correct_answer - 正确答案
   * @param {number} params.score - 分值
   * @param {string} params.analysis - 题目解析
   * @param {array} params.media_files - 媒体文件
   * @param {string} params.userId - 用户ID
   * @returns {object} 保存结果
   */
  async saveQuestion(params) {
    try {
      const db = uniCloud.database();
      const {
        title,
        type,
        options,
        correct_answer,
        score,
        analysis,
        media_files,
        userId
      } = params;

      // 验证必填参数
      if (!title || !type || !correct_answer) {
        return {
          code: -1,
          message: '题目标题、类型和正确答案为必填项'
        };
      }

      // 验证选项
      if (type === 'single' || type === 'multiple') {
        if (!Array.isArray(options) || options.length < 2) {
          return {
            code: -1,
            message: '选择题必须包含至少两个选项'
          };
        }
      }

      // 构建题目数据
      const questionData = {
        title,
        type,
        options: options || [],
        correct_answer,
        score: score || 1,
        analysis: analysis || '',
        media_files: media_files || [],
        creator_id: userId,
        create_date: new Date(),
        update_date: new Date()
      };

      // 保存到数据库
      const result = await db.collection('exam_questions').add(questionData);

      return {
        code: 0,
        message: '保存成功',
        data: {
          _id: result.id,
          ...questionData
        }
      };
    } catch (error) {
      console.error('保存题目失败:', error);
      return {
        code: -1,
        message: '保存题目失败: ' + error.message
      };
    }
  },

  /**
   * 获取考试详细统计信息
   * @param {object} params - 参数对象
   * @param {string} params.examId - 考试ID
   * @param {string} params.type - 统计类型：'basic'|'score_distribution'|'error_questions'
   * @returns {object} 统计信息
   */
  async getExamDetailStatistics(params) {
    try {
      const { examId, type = 'basic' } = params;
      
      if (!examId) {
        return {
          code: -1,
          message: '考试ID不能为空'
        };
      }
      
      const db = uniCloud.database();
      const $ = db.command.aggregate;
      
      // 获取考试记录
      const records = await db.collection('exam_records')
        .aggregate()
        .match({
          exam_id: examId,
          status: 'completed'
        })
        .end();
        
      const recordList = records.data || [];
      
      // 基础统计
      const basicStats = {
        participantCount: recordList.length,
        avgScore: 0,
        passRate: 0,
        highestScore: 0
      };
      
      if (recordList.length > 0) {
        const scores = recordList.map(r => r.score || 0);
        basicStats.avgScore = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
        basicStats.highestScore = Math.max(...scores);
        
        // 获取考试及格分数
        const exam = await db.collection('exam_papers').doc(examId).get();
        const passScore = exam.data && exam.data.length > 0 ? (exam.data[0].pass_score || 60) : 60;
        
        const passCount = scores.filter(s => s >= passScore).length;
        basicStats.passRate = Math.round((passCount / scores.length) * 100);
      }
      
      // 根据类型返回不同的统计数据
      switch (type) {
        case 'score_distribution':
          // 分数分布统计
          const distribution = {
            '0-59': 0,
            '60-69': 0,
            '70-79': 0,
            '80-89': 0,
            '90-100': 0
          };
          
          recordList.forEach(record => {
            const score = record.score || 0;
            if (score < 60) distribution['0-59']++;
            else if (score < 70) distribution['60-69']++;
            else if (score < 80) distribution['70-79']++;
            else if (score < 90) distribution['80-89']++;
            else distribution['90-100']++;
          });
          
          return {
            code: 0,
            data: {
              scoreDistribution: Object.entries(distribution).map(([range, count]) => ({
                range,
                count,
                percentage: recordList.length > 0 ? Math.round((count / recordList.length) * 100) : 0
              }))
            }
          };
          
        case 'error_questions':
          // 错题分析
          const questionStats = {};
          
          recordList.forEach(record => {
            if (!record.answers || !Array.isArray(record.answers)) return;
            
            record.answers.forEach((answer, index) => {
              if (!questionStats[index]) {
                questionStats[index] = {
                  correctCount: 0,
                  wrongCount: 0
                };
              }
              
              if (answer.isCorrect) {
                questionStats[index].correctCount++;
              } else {
                questionStats[index].wrongCount++;
              }
            });
          });
          
          const errorQuestions = Object.entries(questionStats).map(([index, stats]) => {
            const totalAttempts = stats.correctCount + stats.wrongCount;
            return {
              questionIndex: parseInt(index) + 1,
              errorRate: totalAttempts > 0 ? Math.round((stats.wrongCount / totalAttempts) * 100) : 0,
              correctCount: stats.correctCount,
              wrongCount: stats.wrongCount
            };
          }).sort((a, b) => b.errorRate - a.errorRate);
          
          return {
            code: 0,
            data: {
              errorQuestions
            }
          };
          
        default:
          // 返回基础统计
          return {
            code: 0,
            data: basicStats
          };
      }
    } catch (error) {
      console.error('获取考试统计信息失败:', error);
      return {
        code: -1,
        message: '获取考试统计信息失败: ' + error.message
      };
    }
  },

  /**
   * 获取考试信息和题目
   * @param {object} params - 参数对象
   * @param {string} params.examId - 考试ID
   * @returns {object} 考试信息和题目列表
   */
  async getExamInfo(params) {
    try {
        const { examId } = params;
        
        if (!examId) {
            return {
                code: -1,
                message: '考试ID不能为空'
            };
        }
        
        const db = uniCloud.database();
        
        // 获取考试基本信息
        const examResult = await db.collection('exam_papers')
            .doc(examId)
            .get();
            
        if (!examResult.data || examResult.data.length === 0) {
            return {
                code: -1,
                message: '考试不存在'
            };
        }
        
        const examInfo = examResult.data[0];
        
        // 检查考试状态
        if (examInfo.status !== 'active') {
            return {
                code: -1,
                message: '该考试已暂停或已结束'
            };
        }

        // 获取题目列表
        let questions = [];
        if (examInfo.questions && Array.isArray(examInfo.questions)) {
            // 从exam_questions集合获取题目详情
            const questionResult = await db.collection('exam_questions')
                .where({
                    _id: db.command.in(examInfo.questions)
                })
                .get();
            
            questions = questionResult.data || [];
        }

        // 如果没有找到题目
        if (questions.length === 0) {
            return {
                code: -1,
                message: '未找到考试题目'
            };
        }
        
        return {
            code: 0,
            message: '获取成功',
            data: {
                examInfo: {
                    _id: examInfo._id,
                    title: examInfo.title || '',
                    duration: examInfo.time_limit || 60,
                    totalScore: examInfo.total_score || 100,
                    passScore: examInfo.pass_score || 60,
                    status: examInfo.status,
                    description: examInfo.description || ''
                },
                questions: questions.map(q => {
                    // 基础字段
                    const questionData = {
                        _id: q._id,
                        content: q.title || '',  // 题目内容在title字段
                        type: q.type === 'judge' ? 'judgment' : q.type, // 统一判断题类型为judgment
                        score: q.score || 5
                    };

                    // 根据题型处理选项和答案
                    if (q.type === 'judge' || q.type === 'judgment') {
                        // 判断题固定选项为"正确"和"错误"
                        questionData.options = ['正确', '错误'];
                        questionData.correct_answer = q.correct_option;
                    } else if (q.type === 'multiple') {
                        // 多选题
                        questionData.options = q.options || [];
                        questionData.correct_answer = q.correct_options || [];
                    } else {
                        // 单选题
                        questionData.options = q.options || [];
                        questionData.correct_answer = q.correct_option || 0;
                    }

                    // 处理媒体文件
                    if (q.media_files && Array.isArray(q.media_files)) {
                        questionData.media = q.media_files;
                    }

                    return questionData;
                })
            }
        };
    } catch (err) {
        console.error('获取考试信息失败:', err);
        return {
            code: -1,
            message: '获取考试信息失败: ' + err.message
        };
    }
},

// 辅助方法：随机打乱数组
shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }
}; 
 